package mybatis.executor;

import mybatis.mapper.MapperStatement;
import mybatis.utils.StringUtils;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cg
 * @date 2023/6/20 14:43
 */
public class ResultSetHandler {

    private MapperStatement mapperStatement;

    public ResultSetHandler(MapperStatement mapperStatement) {
        this.mapperStatement = mapperStatement;
    }

    public <E> List<E> handle(ResultSet resultSet) {
        //获取返回对象
        List<E> result = new ArrayList<>();
        String resultType = mapperStatement.getResultType();
        try {
            Class<?> clazz = Class.forName(resultType);
            //处理结果集
            while (resultSet.next()) {
                Object instance = clazz.getConstructor().newInstance();
                for (Field declaredField : clazz.getDeclaredFields()) {
                    declaredField.setAccessible(true);
                    //驼峰命名转下划线命名
                    String fieldName = StringUtils.camelToUnderscore(declaredField.getName());
                    Class<?> fieldType = declaredField.getType();
                    Object fieldResult = resultSet.getObject(fieldName, fieldType);
                    declaredField.set(instance, fieldResult);
                }
                result.add((E) instance);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
